<?php


namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Linkslists;
use App\Models\Linkslistsminapps;
use App\Models\Miniappsauthorization;
use App\Models\Linkslistsqrcodes;
use App\Models\Linkslistsreports;
use App\Models\Linkslistssetting;
use App\Models\Linksliststhird;
use App\Models\Safeips;
use App\Services\ApisafeService;
use App\Services\WechatopenService;
use App\Services\MiniappService;
use App\Services\OutputService;
use App\Services\CacheService;
use App\Services\HtmlossService;
use App\Jobs\Miniappdisable;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use Log,Exception;

class LinkslistsController extends Controller
{
    public function linksInfo(Request $request)
    {
        $params = ApisafeService::apiAesDecrypt($request->key,$request->timestamp,$request->data);
        if (empty($params)) return response()->json(["status"=>"error","code"=>"1001","msg"=>"接口异常,请联系客服!"]);
        $links_id = $params->links_id;
        $appid = $params->appid;
        $path = $params->path;
        $query = $params->query;
        $miniapp_type = $params->miniapp_type;
        $platfrom_type = $params->platfrom_type;
        $third_appid = isset($params->third_appid) ? $params->third_appid : "";
        if(Cache::has('links_miniapp_'.$links_id)) {
            $miniapp = Cache::get('links_miniapp_'.$links_id);
        } else {
            if ($miniapp_type == 1) {
                // 先获取三方上架的小程序
                $thirdMiniapps = Miniappsauthorization::getMiniappsAuthorizationSimple($appid);
                if (empty($thirdMiniapps)) {
                    HtmlossService::aliossHtmlDelete($links_id,"");
                    return response()->json(["status"=>"error","code"=>"1001","msg"=>"小程序不存在,无法使用!"]);
                }
                // $selfMinapps = Linkslistsminapps::getLinksListsMinappsByAppidSimple($appid);
                // if ($selfMinapps->disable == 2) return response()->json(["status"=>"error","code"=>"1001","msg"=>"小程序已删除,无法使用!"]);
                $miniapp = ["appid"=>$appid,"component_appid"=>$thirdMiniapps->component_appid,"miniapp_type"=>$miniapp_type,"authorizer_refresh_token"=>$thirdMiniapps->authorizer_refresh_token];
            } else {
                $selfMinapps = Linkslistsminapps::getLinksListsMinappsByAppidSimple($appid);
                if (empty($selfMinapps)) {
                    HtmlossService::aliossHtmlDelete($links_id,"");
                    return response()->json(["status"=>"error","code"=>"1001","msg"=>"小程序不存在,无法使用!"]);
                }
                // if ($selfMinapps->disable == 2) return response()->json(["status"=>"error","code"=>"1001","msg"=>"小程序已删除,无法使用!"]);
                $miniapp = ["appid"=>$appid,"component_appid"=>"","miniapp_type"=>$miniapp_type,"secret"=>$selfMinapps->secret,"status"=>$selfMinapps->status,"type"=>$selfMinapps->type];
            }
            // 每次调用缓存30分钟
            Cache::put('links_miniapp_'.$links_id, $miniapp, 1800);
        }

        if (in_array($platfrom_type, [1,2,3,6,8,9,11,12,13])) {
            if(strpos($query,'id=') !== false){
                $query = $query."&key=".$request->key."&timestamp=".$request->timestamp."&nsign=".$request->sign;
            }else{
                $query = $query."&key=".$request->key."&timestamp=".$request->timestamp."&nsign=".$request->sign."&id=".$links_id;
            }
        }

        if ($miniapp["miniapp_type"] == 1) {
            try {
                // 获取Token信息
                $access_token = WechatopenService::getMiniProgramAccessToken($miniapp["component_appid"],$miniapp["appid"],$miniapp["authorizer_refresh_token"]);
                $generate =  MiniappService::urlSchemeCreat($access_token,$path,$query);
            } catch (Exception $e) {
                $message = $e->getMessage();
                $message = json_decode(str_replace("Request access_token fail: ", "", $message));
                if ($message->errcode == 40013) return response()->json(["status"=>"error","msg"=>"小程序Appid错误,请确认Appid正确且小程序已上线！"]);
                if ($message->errcode == 40125) return response()->json(["status"=>"error","msg"=>"小程序Appsecret错误,请修改后重新提交！"]);
                if ($message->errcode == 40001) WechatopenService::getMiniProgramAccessToken($miniapp["component_appid"],$miniapp["appid"],$miniapp["authorizer_refresh_token"]);
                if ($message->errcode == 50002) return response()->json(["status"=>"error","msg"=>"小程序已被注销或封禁,请修改小程序！"]);
                if ($message->errcode == 61003) return response()->json(["status"=>"error","msg"=>"小程序未授权给天天外链！"]);
                Log::info("--------");
                Log::info(json_encode($e));
                Log::info(json_encode($params));
                Log::info("--------");
                return response()->json(["status"=>"error","msg"=>"小程序异常,请联系客服！"]);
            }
        } elseif ($miniapp["miniapp_type"] == 3) {
            // 自定义接口获取token
            try {
                $generate = MiniappService::apiTypeUrlScheme($miniapp["appid"],$path,$query);
            } catch (Exception $e) {
                Log::info(json_encode($params));
                return response()->json(["status"=>"error","msg"=>"小程序异常,请联系客服！"]);
            }
        } else {
            try {
                $generate = MiniappService::getUrlScheme($miniapp["appid"],$miniapp["secret"],$path,$query);
            } catch (Exception $e) {
                Log::info(json_encode($params));
                return response()->json(["status"=>"error","msg"=>"小程序异常,请联系客服！"]);
            }
        }
        if ($generate["status"] == "error") {
            // 小程序已被封禁
            if ($generate["code"] == 50002 || $generate["code"] == 40013) {
                $minappsDisableStatus = Redis::hexists("links_lists_minapps_disable", $miniapp["appid"]);
                if (!$minappsDisableStatus) {
                    // 加入队列
                    Miniappdisable::dispatch($miniapp["appid"],4)->delay(1);
                    Redis::hset("links_lists_minapps_disable", $miniapp["appid"], "1");
                    Log::info("-----------------");
                    Log::info($generate);
                    Log::info(json_encode($params));
                    Log::info("-----------------");
                }
            } elseif ($generate["code"] == 40001) {
                if ($miniapp["miniapp_type"] == 1) WechatopenService::getMiniProgramAccessToken($miniapp["component_appid"],$miniapp["appid"],$miniapp["authorizer_refresh_token"]);
            }
            return $generate;
        }
        $data = ApisafeService::apiAesEncrypt($request->key,$request->timestamp,json_encode(["urlscheme"=>$generate["urlscheme"]]));
        return response()->json(["status"=>"success","code"=>"1000","msg"=>"接口获取成功!","data"=>$data]);
    }

    public function linksMiniappInfo(Request $request,$version)
    {
        $linksId = explode("_",$request->links_id);
        $links_id = $linksId[0];
        if(Cache::has('links_api_'.$links_id)) {
            $links = Cache::get('links_api_'.$links_id);
        } else {
            $links = Linkslists::jumpGetApiLinks($links_id);
            if (empty($links)) return OutputService::error("您访问的链接不存在！");
            if ($links->disable != 1) return OutputService::error("链接已删除！");
            if ($links->limit_status == 1 && $links->left_pv <= 0) return OutputService::error("链接访问次数不足,请充值！");
            if ($links->limit_pv > 1000 && $links->end_time < time()) return OutputService::error("会员已过期,请续费后访问充值！");
            if ($links->limit_pv < 1000 && $links->end_time < time()) return OutputService::error("免费体验已过期1小时,请开通会员后访问！");
            if ($links->platfrom_type == 6) {
                $third = Linksliststhird::getLinksListsThird($links_id);
                $links->msg = json_encode(["mini_id"=>$third->appid,"path"=>$third->path,"original_id"=>$third->original_id]);
            }
            // 获取小程序内样式
            $linksSetting = Linkslistssetting::getLinksListsSetting($links_id);
            $links = collect($links)->merge($linksSetting)->all();

            // 每次调用缓存30分钟
            Cache::put('links_api_'.$links_id, $links, 1800);
        }

        if (in_array($links["platfrom_type"], [8,9,11,12])) {
            $batch = date("Ymd");
            $qrcodes = Redis::hget("links_qrcodes_".$batch, $links_id);
            if (empty($qrcodes)) {
                // 更新昨天二维码数据并且删除缓存
                CacheService::removeLinksQrcodeCache($links_id,date("Ymd",strtotime("-1 day")));
                $qrcodes = Linkslistsqrcodes::getAllLinksListsQrcodes($links_id);
                if (empty($qrcodes)) return OutputService::error("当前暂无可用二维码！");
                Redis::hset("links_qrcodes_".$batch, $links_id, json_encode($qrcodes));
            } else {
                $qrcodes = json_decode($qrcodes);
            }
            if (empty($qrcodes)) return OutputService::error("当前暂无可用二维码！");
            $qrcode_image = "";
            $qrcodes_id = "";
            if ($links["qrcode_switch"] == 2){
                try {
                    $qrcodeCount = count($qrcodes);
                } catch (Exception $e) {
                    $qrcodeCount = count($qrcodes->toArray());
                }
                // 随机二维码
                if ($qrcodeCount >= 0) {
                    $key = rand(0,$qrcodeCount-1);
                } else {
                    $key = 0;
                }
                $qrcodes[$key]->scan_total += 1;
                $qrcodes[$key]->scan_today += 1;
                $qrcode_image = $qrcodes[$key]->img_url;
                $qrcodes_id = $qrcodes[$key]->qrcodes_id;
            } else {
                $qrcodes = collect($qrcodes);
                if ($links["qrcode_switch"] == 1) {
                    // 顺序切换
                    $qrcodes = $qrcodes->sortByDesc('rate')->all();
                } else {
                    // 循环切换
                    $qrcodes = $qrcodes->sortBy('scan_today')->all();
                }
                foreach ($qrcodes as $key => $qrcode) {
                    if ($links["qrcode_upper"] == 1) {
                        // 累计上限
                        if ($qrcode->scan_total < $qrcode->count_limit) {
                            $qrcodes[$key]->scan_total += 1;
                            $qrcodes[$key]->scan_today += 1;
                            $qrcode_image = $qrcode->img_url;
                            $qrcodes_id = $qrcode->qrcodes_id;
                            break;
                        }
                    } else {
                        // 每日上限
                        if ($qrcode->scan_today < $links["qrcode_daily"]) {
                            $qrcodes[$key]->scan_total += 1;
                            $qrcodes[$key]->scan_today += 1;
                            $qrcode_image = $qrcode->img_url;
                            $qrcodes_id = $qrcode->qrcodes_id;
                            break;
                        }
                    }
                }
            }
            if (empty($qrcode_image)) return OutputService::error("当前暂无二维码,请查看二维码设置的二维码有效期和访问上限！");
            Redis::hset("links_qrcodes_".$batch, $links_id, json_encode($qrcodes));
            if ($version >= 3){
                $links["msg"] = $qrcode_image;
            } else {
                $links["msg"] = json_encode([$qrcode_image]);
            }
            $links["qrcodes_id"] = $qrcodes_id;
        } else {
            $links["qrcodes_id"] = "";
        }

        if ($version >= 3) return OutputService::success("Success",$links);

        //公众号二维码模式兼容以前上架的小程序
        $platfrom_type = $links["platfrom_type"] == 12 ? 11 : $links["platfrom_type"];
        if ($version <= 1) {
            // 摩尔活码
            if ($links["platfrom_type"] == 13) {
                $platfrom_type = 1;
            }
        }
        $describe_show = in_array($links["platfrom_type"],[2,3,6]) ? $links["button_show"] : $links["miniapp_style"];
        $describe = in_array($links["platfrom_type"],[2,3,6]) ? $links["button_text"] : $links["describe"];
        $data = ["title"=>"","nike"=>$links["nike"],"platfrom_type"=>$platfrom_type,"describe"=>$describe,"type"=>$links["type"],"msg"=>$links["msg"],"status"=>1,"links_id"=>$links["links_id"],"image"=>$links["logo"],"notice"=>$links["button_text"],"describe_show"=>$describe_show,"notice_img"=>$links["logo"],"wechat"=>"","text"=>$links["qrcode_notice"],"image_notice"=>"","qrcodes_id"=>$links["qrcodes_id"]];
        if ($version < 3) {
            $data = ApisafeService::apiAesEncrypt($request->key,$request->timestamp,json_encode($data));
        }
        return OutputService::success("SUCCESS",$data);
    }

    public function linksMiniappReport(Request $request,$version)
    {
        if (empty($request->links_id) || empty($request->appid) || empty($request->message)) return response()->json(["status"=>"error","code"=>"1001","msg"=>"接口异常请稍后访问!"]);
        $ip = isset($_SERVER["HTTP_ALI_CDN_REAL_IP"]) ? $_SERVER["HTTP_ALI_CDN_REAL_IP"] : $_SERVER["REMOTE_ADDR"];
        Linkslistsreports::insertLinksListsReports($request->links_id,$request->report,$request->appid,$request->message,$ip);
        return response()->json(["status"=>"success","code"=>"1000","msg"=>"投诉成功,我们会在一个工作日内处理!"]);
    }

    public function linksSafe(Request $request)
    {
        $ip = isset($_SERVER["HTTP_ALI_CDN_REAL_IP"]) ? $_SERVER["HTTP_ALI_CDN_REAL_IP"] : $_SERVER["REMOTE_ADDR"];
        if (mb_strlen($request->links_id) >= 16) {
            Log::info("linksSafe--------------");
            Log::info($request->all());
            Log::info("linksSafe--------------");
        }
        if (mb_strlen($request->users_lists) >= 30) {
            Log::info("linksSafe--------------");
            Log::info($request->all());
            Log::info("linksSafe--------------");
        }
        Safeips::insertSafeIps($ip,$request->links_id,$request->users_lists,1);
    }

    public function linksError(Request $request)
    {
        // Log::info("linksError--------------");
        // Log::info($request->all());
        // $ip = isset($_SERVER["HTTP_ALI_CDN_REAL_IP"]) ? $_SERVER["HTTP_ALI_CDN_REAL_IP"] : $_SERVER["REMOTE_ADDR"];
        // $agent = $_SERVER['HTTP_USER_AGENT'];
        // Log::info($agent);
        // Log::info("linksError--------------");
    }
}